package org.proddevplm.dao.core;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.proddevplm.dao.api.IActivityMgmt;
import org.proddevplm.dao.data.activities.Activity;
import org.proddevplm.dao.util.HibernateUtil;

public class ActivityMgmt implements IActivityMgmt{

	@Override
	public boolean addActivity(Activity activity) {
		
		HibernateUtil.currentSession().persist(activity);
		
		return false;
	}

	@Override
	public List<Activity> getActivitiesByProductId(int productId) {
		
		Session session = HibernateUtil.currentSession();
		Query q = session.createQuery("select a from Activity a where a.productId=:productId");
		q.setInteger("productId", productId);
		return q.list();
	}

	@Override
	public Activity getActivityByNameandProductId(String name, int productId) {
		Session session = HibernateUtil.currentSession();
		Query q = session.createQuery("select a from Activity a where a.name=:name and a.productId=:productId");
		q.setString("name", name);
		q.setInteger("productId", productId);
		return (Activity)q.uniqueResult();
	}

	@Override
	public boolean updateActivity(Activity activity) {
		
		HibernateUtil.currentSession().merge(activity);
		
		return false;
	}

	@Override
	public List<Activity> getActivityByUserandProductId(String user,
			int productId) {
		Session session = HibernateUtil.currentSession();
		Query q = session.createQuery("select a from Activity a where a.responsible=:user and a.productId=:productId");
		q.setString("user", user);
		q.setInteger("productId", productId);
		return q.list();
	}

	@Override
	public List<Activity> getActivityByRoleandProductId(String role,
			int productId) {
		Session session = HibernateUtil.currentSession();
		String allRoles = "All roles";
		Query q = session.createQuery("select a from Activity a where (a.responsible=:role or a.responsible=:allRoles) and a.productId=:productId");
		q.setString("role", role);
		q.setString("allRoles", allRoles);
		q.setInteger("productId", productId);
		return q.list();
	}

	@Override
	public boolean removeActivity(String name, int productId) {
		Session session = HibernateUtil.currentSession();
		Query q = session.createQuery("delete from Activity a where a.name=:name and a.productId=:productId");
		q.setString("name", name);
		q.setInteger("productId", productId);
		q.executeUpdate();
		return false;
	}

}
